import { Toast } from '@tencent/corgi-ui'
import $request from './request'
import $api from '../model/api'
import $user from '../model/user'
import $env from '../model/env'
import { jsbridge, getCCTVJsApi } from '../util/cctvJsApi'

const Api = {}

function getTs () {
	let time = Math.floor(new Date().getTime() / 2000)
	if (time % 2 > 0) {
		time = time + 1
	}
	return time
}

// 点播评论
Api.videoCommentList = (data) => {
	data = data || {}
	data.ts = getTs()
	$request({
		url: $api['video-comment-list'],
		withCredentials: false,
		type: 'get',
		data,
		resolveErrorMsg(msg) {
			console.error([
				'点播评论列表数据加载失败',
				msg
			].join('\n'))
		}
	})
}

// 直播评论
Api.liveCommentList = (data) => {
	data = data || {}
	data.ts = getTs()
	return $request({
		url: $api['live-comment-list'],
		withCredentials: false,
		type: 'get',
		data,
		resolveErrorMsg(msg) {
			console.error([
				'直播评论列表数据加载失败',
				msg
			].join('\n'))
		}
	})
}

// 直播轮询
Api.livePoll = (data) => {
	data = data || {}
	data.ts = getTs()
	return $request({
		url: $api['live-poll'],
		withCredentials: false,
		type: 'get',
		data,
		resolveErrorMsg(msg) {
			console.error([
				'直播状态加载失败',
				msg
			].join('\n'))
		}
	})
}

// 直播发表评论
Api.sendLiveComment = data => $request({
	url: $api['live-comment'],
	type: 'post',
	data: JSON.stringify(data),
	contentType: 'application/json',
	dataType: 'json',
	async resolveErrorMsg(msg) {
		msg = msg || ''
		// 15006 错误是鉴权失败
		if (msg.indexOf('15006') >= 0) {
			const res = await $user.isSigned()
			if (!res) {
				// 未登录就唤起登录
				$user.signin()
			} else if ($env.isYSP) {
				// 旧版客户端内可能票据未刷新
				// 所以要重新登录
				await getCCTVJsApi()
				await jsbridge.ready()
				await jsbridge.logout()
				await jsbridge.invokeLogin()
			} else {
				// 端外可能是cookie过期，重新登录
				await $user.signout()
				$user.signin()
			}
		} else {
			Toast.fail([
				'发表评论失败',
				msg
			].join('\n'), 2)
		}
	}
})

export default Api
